<template>
    <tablePaging :tableItem="tableItem" :operationItem="operationItem">
        <template v-slot:actionCustom="scope">
            <el-button v-hasPermi="[$button.courseorderview || null]" link @click="detailHandle(scope, 'view')" type="primary" size="small">查看</el-button>
            <!-- 已付款没开票的 是申请开票 -->
            <el-button v-hasPermi="[$button.courseorderInvoiceadd || null]"
                v-if="scope.scope.scope.row.statusCode == 'paid' && scope.scope.scope.row.invoiceFlag !== 1" link
                @click="operateHandle('invoicing', scope)" type="primary" size="small">申请开票</el-button>
            <!-- 已付款的并且没有退款在进行中的是申请退款 -->
            <el-button v-hasPermi="[$button.courseorderRefundadd || null]"
                v-if="scope.scope.scope.row.statusCode == 'paid' && scope.scope.scope.row.refundStatusCode !== 'refunding'"
                link @click="detailHandle(scope, 'refund')" type="primary" size="small">申请退款</el-button>
            <!-- 线下支付的待付款的确认打款 -->
            <el-button v-hasPermi="[$button.courseorderpay || null]"
                v-if="scope.scope.scope.row.statusCode == 'payAuditing' || scope.scope.scope.row.statusCode == 'paying'"
                link @click="operateHandle('examine', scope)" type="primary" size="small">确认打款</el-button>
            <!-- 用户申请退款的是处理退款 -->
            <el-button v-hasPermi="[$button.courseorderRefundaudit || null]"
                       v-if="scope.scope.scope.row.statusCode == 'paid' && scope.scope.scope.row.refundStatusCode == 'refunding'
                       && scope.scope.scope.row.refundPayoutStatusCode === 'non'"
                       link @click="operateHandle('refundsProcess', scope)" type="primary" size="small">处理退款</el-button>
            <el-button v-hasPermi="[$button.courseorderRefundaudit || null]"
                       v-if="scope.scope.scope.row.refundStatusCode == 'refunding' && scope.scope.scope.row.refundPayoutStatusCode == 'pending'"
                       link @click="operateHandle('refundRequest', scope)" type="primary" size="small">上传退款单</el-button>
        </template>
    </tablePaging>
    <fileImport v-model:importVisible="data.importVisible" :importItem="importItem" @onSuccess="onSuccess"
        @onError="onError" @successResult="successResult" />
    <!-- 弹窗处理 -->
    <DialogHandle @confirmHandle="confirmHandle" @closeHandle="closeHandle" :data="data"></DialogHandle>
</template>
<script setup>
import fileImport from '@/views/common/component/fileImport'
import { ref, watch, reactive, getCurrentInstance, onMounted } from "vue"
import tablePaging from '@/views/common/component/table-paging'
import $button from '@/button'
import DialogHandle from './component/dialog-handle'
import { ElMessage, ElMessageBox } from 'element-plus'
import { refundAgreeApi, tableItem, operationItem, OrderTemplateApi, invoicingApi, payConfirmApi, refundPayoutApi } from './const.js'
import { useRouter, useRoute } from 'vue-router'
import {orderDetailApi} from './component/const'
import {validateTaxIdentificationNumber} from '../../../utils/validate'
const router = useRouter()
const importItem = reactive({
    downUrl: '/order/import/template',
    upUrl: '/order/import/template',
    blob: true,//二进制文件下载,
    // method: 'GET',
    data: { method: 'GET', saleId: '' },
    downName: '订单导入模版',
})
const data = reactive({
    importVisible: false,
    orderDialog: false,
    dialogTitle: '选择商家',
    //import导入名单 invoicing 开票 examine 审核
    handleOrderType: 'import',
    request: {
        import: { id: '' },
        invoicing: {
            "orderId": "",
            "titleTypeCode": "enterprise",//"person"-个人 "enterprise"-企业
            "title": "",
            "taxIdentificationNumber": "",
            "address": "",
            "mobile": "",
            "bankName": ""
        },
        examine: {
            "id": '', //订单id
            "payPrice": '', //实付金额
            "payTime": "", //支付时间
            "payDescription": "", //打款说明
            "payReceiptUrl": "" //打款证明地址
        },
        refundsProcess: {
            "orderId": '', //订单id
            "auditDescription": "",//审核说明
            "refundList": [],//退款列表
            'refundReason': ''
        },
        refundRequest: {
            "orderId": '', //订单号
            "payoutDate": "", //打款日期
            "finalPrice": '',//退款金额
            "payoutReceiptUrl": "" //打款单},
        },
    },
    formRules: {
        title: [{ required: true, message: '请输入发票抬头', trigger: 'blur' },],
        taxIdentificationNumber: [{ required: true, validator: validateTaxIdentificationNumber, trigger: 'blur' },],
        titleTypeCode: [{ required: true, message: '请选择类型', trigger: 'blur' },],
        payPrice: [{ required: true, message: '请选择开票类型', trigger: 'blur' },],
        payTime: [{ required: true, message: '请选择打款时间', trigger: 'change' },],
        payoutDate: [{ required: true, message: '请选择退款日期', trigger: 'change' },],
        finalPrice: [{ required: true, message: '请输入退款金额', trigger: 'blur' },],
        payDescription: [{ required: true, message: '请输入打款说明', trigger: 'blur' },],
        payReceiptUrl: [{ required: true, message: '请上传打款凭证', trigger: 'change' },],
        payDate: [{ required: true, message: '请选择打款日期', trigger: 'change' },],
        payoutReceiptUrl: [{ required: true, message: '请上传打款单', trigger: 'change' },],
        // sale: [{ required: false, message: '请选择商家名称', trigger: 'change' },],
    }
})
const formSale = ref(null)
onMounted(() => {
    operationItem.menuArray[0].handle = () => { operateHandle('import') }
})
const detailHandle = (res, type) => {
    const scope = res.scope.scope
    router.push({
        path: '/modules/order/component',
        query: { id: scope.row.id || '', type: type }
    })
}

const onSuccess = () => {
    tableItem.pageInfo.paging();
    data.importVisible = false;
}
const onError = () => {

}
const successResult = () => {

}
const operateHandle = (type, res) => {
    data.handleOrderType = type
    let scope = {}
    if (res) {
        scope = res.scope.scope
        data.row = scope.row
    }
    switch (type) {
        case 'import':
          data.dialogTitle = '选择商家'; break;
        case 'invoicing':
            for (const key in data.request.invoicing) {
                if (key != 'titleTypeCode') { data.request.invoicing[key] = '' }
            };
            data.request.invoicing.orderId = scope.row.id
            data.dialogTitle = '申请开票'; break;
        case 'examine':
            data.dialogTitle = '确认打款';
            data.request.examine.id = scope.row.id;
            data.request.examine.payTime = scope.row.payTime;
            data.request.examine.payPrice = scope.row.price;
            data.request.examine.payReceiptUrl = scope.row.payReceiptUrl;
            break;
        case 'refundsProcess':
            data.request.refundsProcess.orderId = scope.row.id;
            data.request.refundRequest.orderId = scope.row.id;
            let dataRequest = {
              orderId: scope.row.id,
              refundStatusCode: 'refunding'
            }
            orderDetailApi(dataRequest).then((res) => {
              data.request.refundsProcess.refundList = []
              data.request.refundsProcess.refundList.push(...res.rows)
            })
            data.dialogTitle = '处理退款';
            break;
        case 'refundRequest':
            data.request.refundRequest.orderId = scope.row.id;
            data.dialogTitle = '上传退款单';
            break;
    }
    data.orderDialog = true
}
const confirmHandle = (info) => {
    switch (data.handleOrderType) {
        case 'import':
            importItem.data.saleId = data.request.import.id;
            data.importVisible = true;
            data.orderDialog = false;
            break;
        case 'invoicing': invoicingApi(data.request.invoicing).then((res) => {
          if(res.code === 200) {
            successHandle(res)
          } else {
            failHandle(res)
          }
        }); break;
        case 'examine':
            payConfirmApi(data.request.examine).then((res) => {
              if(res.code === 200) {
                successHandle(res)
              } else {
                failHandle(res)
              }
            }); break;
        case 'refundRequest':
            refundPayoutApi(data.request.refundRequest).then((res) => {
              if(res.code === 200) {
                successHandle(res)
              } else {
                failHandle(res)
              }
            });break;
    }
}
const closeHandle = () => {
    data.request.examine.payReceiptUrl = "";
  tableItem.pageInfo.paging()
}
const successHandle = (res) => {
  ElMessage.success(res.msg)
  data.orderDialog = false;
  tableItem.pageInfo.paging()
}
const failHandle = (res) => {
  ElMessage.error(res.msg)
}

</script>
<style lang="scss">
.sharing-code-dialog {
    .el-dialog__body {
        padding: 0;
        height: 0;
    }

    .el-dialog__header {
        padding: 0;
        border-radius: 20px;
    }
}
</style>
<style lang="scss" scoped>
.item-input-width {
    width: 785px;
}

.sharing-code-content {
    color: #409EFF;
    padding: 30px;
    font-size: 14px;
    font-family: DingTalk JinBuTi;
    font-weight: 400;
    display: flex;
    flex-direction: column;
    align-items: center;
    position: absolute;
    top: 50px;
    left: 40px;
    width: 400px;
    height: 458px;
}
</style>
